<?php
namespace Admin\Controller;

/**
 *	操作标签控制器
 *  @version 0.0.1
 * 	@author Lwbang<375500819@qq.com>
 */
class TagController extends AuthController {

	private $model;

	protected function _initialize() {
		$this -> model = D('Tag');
	}

	/**
	 * 删除标签  关联删除相应文章表和标签中间表的相应ID
	 * @return String
	 */
	public function delTag() {
		if (IS_POST) {
			$tid = I('post.tid', 0, 'intval');
			if ($this -> model -> delete($tid)) {
				//删除相应中间标签tag_tid=$tid的行
				M('articleTag') -> where(array('tag_tid' => $tid)) -> delete();
				$this->ajaxReturn(array('status'=>1,'msg'=>'删除成功'));
			}
		}
		$this->error('非法请求',U('Index/index'));
	}

	/**
	 * 添加标签
	 * @return String
	 */
	public function addTag() {
		//标签名称
		$tagName = I('post.tag_name', '', 'strval');
		$result = $this -> model -> where(array('tag_name' => $tagName)) -> find();
		if ($result) {
			$this -> ajaxReturn(array('status' => 0, 'msg' => '标签已存在请更换'));
		}
		//如果不存在那么将标签写入数据库
		if ($this -> model -> create()) {
			$tid = $this -> model -> add();
			$data = $this->model->where(array('tag_id'=>$tid))->find();
			$this -> ajaxReturn(array('status' => 1, 'msg' => '添加新标签成功','data'=>$data));
		}else{
			$this -> ajaxReturn(array('status' => 0, 'msg' => $this->model->getDbError()));
		}

	}

	/**
	 * 修改一个标签
	 * @return String
	 */
	 public function editTag(){
	 	if(IS_POST){
	 		//查询当前提交过来的标签名是否已经存在 排除当前的修改的标签名
	 		//如果存在返回真否则 返回false
	 		if(!$this->model->isExists(I('post.tag_name'),I('post.tag_id'))){
	 			//当不存在那么就修改他
	 			$this->ajaxReturn(array('status'=>0,'msg'=>'要修改的标签名已经存在请更换'));	
	 		}else{
	 			if($this->model->edit()){
	 				$this->ajaxReturn(array('status'=>1,'msg'=>'保存成功','data'=>$_POST));	
	 			}
	 			$this->ajaxReturn(array('status'=>0,'msg'=>$this->model->getError()));	
	 		}	
	 	}
	 }
	
	/**
	 * 显示首页信息
	 * @return void
	 */
	public function index() {
		//查询所有的标签
		$tags = $this -> model -> order('tag_id DESC') -> select();
		$this -> assign('tags', $tags);
		$this -> display();
	}

}
